import { defineStore } from 'pinia';
import axios from 'axios';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null, // 存储用户信息
    isAuthenticated: false, // 状态
    role: null 
  }),
  actions: {
    async login(username, password) {
      try {
        const response = await axios.post('/api/login', { username, password });
        this.user = response.data.user; 
        this.isAuthenticated = true;
        this.role = response.data.user.role;
        return true;
      } catch (error) {
        console.error('登录失败', error);
        return false;
      }
    },
    async register(username, password) {
      try {
        const response = await axios.post('/api/register', { username, password });
        return response.data.success; 
      } catch (error) {
        console.error('注册失败', error);
        return false;
      }
    },
    logout() {
      this.user = null;
      this.isAuthenticated = false;
      this.role = null;
    }
  }
});